
import Foundation
import UIKit

extension JX_TypeWrapper where T : UIApplication{
    
    public static func getPreviousController(currentViewController:UIViewController)->(UIViewController?){
        
        if currentViewController.navigationController != nil{
            let navCon = currentViewController.navigationController!
            return navCon.viewControllers[navCon.viewControllers.count - 2]
        }else{
            return nil
        }
    }
    
    
    public func currentController()->UIViewController?{
        
        if SELF.delegate?.window == nil {return nil}
        var normalWindow = SELF.delegate?.window!
        if normalWindow?.windowLevel != UIWindowLevelNormal {
            for obj in SELF.windows {
                if obj.windowLevel == UIWindowLevelNormal {
                    normalWindow = obj
                    break
                }
            }
        }
        
        return p_nextTop(for: normalWindow?.rootViewController)
        
    }
    
    
    fileprivate func p_nextTop(for inViewController: UIViewController?) -> UIViewController? {
        var inViewController = inViewController
        while ((inViewController?.presentedViewController) != nil) {
            inViewController = inViewController?.presentedViewController
        }
        if (inViewController is UITabBarController) {
            let selectedVC: UIViewController? = p_nextTop(for: (inViewController as? UITabBarController)?.selectedViewController)
            return selectedVC
        } else if (inViewController is UINavigationController) {
            let selectedVC: UIViewController? = p_nextTop(for: (inViewController as? UINavigationController)?.visibleViewController)
            return selectedVC
        } else {
            return inViewController
        }
    }
    
}
